/**
 * Created by zhaoyue on 2017/5/1.
 */
import { call, put, takeEvery } from 'redux-saga/effects'

export const ADD_TOAST = 'ADD_TOAST'
export const BURN_TOAST = 'BURN_TOAST'

let toastID = 0
const initialState = []

export function addToast(toast) {
	return {
		type: ADD_TOAST,
		payload: {
			id: toastID++,
			message: toast,
		},
	}
}

export function burnToast(id) {
	return {
		type: BURN_TOAST,
		payload: id,
	}
}

function toast(state = initialState, action = {}) {
	switch (action.type) {
		case ADD_TOAST:
			return state.concat(action.payload)
		case BURN_TOAST:
			const id = action.payload
			const burnIndex = Array.findIndex(state, (item) => item.id === id)
			const stateLen = state.length
			return state.slice(0, burnIndex).concat(state.slice(burnIndex + 1, stateLen))
		default:
			return state
	}
}

const TOAST_TIMEOUT = 3000

const wait = (ms) =>
	new Promise((resolve) => {
		setTimeout(() => resolve(), ms)
	})

function* onToastAdded({ payload }) {
	try {
		if (process.env.NODE_ENV !== 'production') {
			console.log('onToastAdded:', payload)
		}
		if (payload.time !== Infinity) {
			yield call(wait, payload.timeout || TOAST_TIMEOUT)
			yield put(burnToast(payload.id))
		}
	} catch (error) {}
}

export default {
	reducer: {
		toast,
	},
	*saga() {
		yield takeEvery(ADD_TOAST, onToastAdded)
	},
}
